package com.kexun.lxj;


/*使用同步方法解决线程问题
* 把共享数据的代码抽取出来,放到一个方法中
* 在方法上添加synchronized修饰符
*
*同步方法的锁对象默认 就是Runnable接口的实现类对象*/
public class Demo02 {
    public static void main(String[] args) {


    Runnable r =new Ticket3();

    //创建四个线程,卖同一个资源
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r);
    Thread t3 = new Thread(r);
    Thread t4= new Thread(r);
        t1.start();
        t2.start();
        t3.start();
        t4.start();

        System.out.println(t1);
    }
}
class Ticket3 implements Runnable {

    private static int i = 20;

    @Override
    public void run() {
        while (true) {

      //   sellTicket();
        sellTicket2();
            if(i==0){
                break;
            }
        }
    }

    public synchronized void sellTicket() {
        System.out.println(this);
        if (i > 0) {
            try {
                System.out.println("这是" + Thread.currentThread().getName() + "卖出的第" + i-- + "张票");
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "卖完了,关闭卖票窗口");

        }
    }

    public  void sellTicket2() {
           synchronized (this){
               System.out.println(this);
               if (i > 0) {
                   try {
                       System.out.println("这是" + Thread.currentThread().getName() + "卖出的第" + i-- + "张票");
                       Thread.sleep(50);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               } else {
                   System.out.println(Thread.currentThread().getName() + "卖完了,关闭卖票窗口");

               }
           }
    }

}